package com.jeremyfeinstein.utils;

import android.content.Context;
import android.net.TrafficStats;

public class NetTxSpeedUtil {
    private static long lastTotalTxBytes = 0;
    private static long lastTimeStamp = 0;

    public static long getTxNetSpeed(Context mContext) {
        long nowTotalTxBytes = getTotalTxBytes(mContext);
        long nowTimeStamp = System.currentTimeMillis();
        long speed = 0;
        if (nowTimeStamp!=lastTimeStamp) {
            // 毫秒转换
            speed = ((nowTotalTxBytes - lastTotalTxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));
        }
        lastTimeStamp = nowTimeStamp;
        lastTotalTxBytes = nowTotalTxBytes;

        return speed;
    }

    private static long getTotalTxBytes(Context mContext) {
        //注 这里取到的时发送的字节数（上传）
        // 转为KB
        return TrafficStats.getUidTxBytes(mContext.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0
                : (TrafficStats.getTotalTxBytes() / 1024);//转为KB
    }

    private static long getTotalRxBytes(Context mContext) {
        //注 这里取到的是总的接收的字节数（下行）
        // 转为KB
        return TrafficStats.getUidRxBytes(mContext.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0
                : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
    }

}
